from flask_wtf import FlaskForm
from wtforms import SelectField, StringField, SubmitField
from wtforms.validators import DataRequired, Length, Optional
from app.models.category import Category


class CategoryForm(FlaskForm):
    pid = SelectField('父栏目',
                      validators=[Optional()],
                      coerce=int,
                      choices=[(0, '选择栏目')])
    title = StringField('栏目名称', validators=[DataRequired(), Length(1, 20)], render_kw={'placeholder': '输入栏目名称'})
    submit = SubmitField('提交')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.pid.choices.extend([(i['id'], i['title']) for i in Category.tree()])

    def load(self, data):
        """填充数据
        """
        for k, v in data.__dict__.items():
            if hasattr(self, k):
                self.__dict__[k].data = None if v is None else v
